import 'package:ducafe_ui_core/ducafe_ui_core.dart';
import 'package:flutter/material.dart';
import 'package:flutter_mobx/flutter_mobx.dart';
import 'package:hinge/common/index.dart';
import 'package:hinge/common/models/topic_comment_model.dart';
import 'package:hinge/store/root_store.dart';
import 'package:mobx/mobx.dart';
import 'package:hinge/common/routers/app_router.dart';

class TopicPage extends StatefulWidget {
  final int topicId;

  const TopicPage({super.key, required this.topicId});

  @override
  State<TopicPage> createState() => _TopicPageState();
}

class _TopicPageState extends State<TopicPage> with RouteAware {
  final TextEditingController _commentController = TextEditingController();
  final _rootStore = RootStore();
  late final _topicStore = _rootStore.topicStore;
  final List<ReactionDisposer> _disposers = [];
  bool _routeIsActive = false;

  @override
  void initState() {
    super.initState();
    // 加载话题数据
    _topicStore.loadTopicData(widget.topicId);

    // 设置输入框监听
    _disposers.add(
      reaction(
        (_) => _topicStore.commentText,
        (String text) => _commentController.text = text,
      ),
    );

    // 设置输入框初始值
    _commentController.addListener(() {
      if (_commentController.text != _topicStore.commentText) {
        _topicStore.setCommentText(_commentController.text);
      }
    });
  }

  @override
  void didChangeDependencies() {
    super.didChangeDependencies();
    final route = ModalRoute.of(context);
    if (route != null) {
      // 订阅路由事件
      AppRouter.routeObserver.subscribe(this, route);
    }
  }

  // 页面变为可见时
  @override
  void didPush() {
    _routeIsActive = true;
    _refreshData();
  }

  // 页面重新变为可见时（比如从登录页面返回）
  @override
  void didPopNext() {
    _routeIsActive = true;
    // 从其他页面（如登录页）返回时，重新检查登录状态并刷新数据
    _refreshData();
  }

  // 页面将被覆盖时
  @override
  void didPushNext() {
    _routeIsActive = false;
  }

  // 页面将被移除时
  @override
  void didPop() {
    _routeIsActive = false;
  }

  // 刷新页面数据和状态
  void _refreshData() {
    print('TopicPage 刷新数据，检查登录状态');
    // 重新检查登录状态
    _topicStore.checkLoginStatus();
    // 重新加载话题数据
    _topicStore.loadTopicData(widget.topicId);
  }

  @override
  void dispose() {
    // 取消路由订阅
    AppRouter.routeObserver.unsubscribe(this);
    // 清理资源
    _commentController.dispose();
    for (final disposer in _disposers) {
      disposer();
    }
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: Container(
        width: double.infinity,
        decoration: BoxDecoration(
          gradient: LinearGradient(
            begin: Alignment(0.50, -0.00),
            end: Alignment(0.50, 1.00),
            colors: [const Color(0xFFA794FD), const Color(0xFFFFEFFA)],
          ),
        ),
        child: SafeArea(
          bottom: false,
          child: Column(
            children: [
              // 顶部导航栏
              _buildAppBar(),

              // 页面内容
              Observer(
                builder:
                    (_) =>
                        _topicStore.isLoading
                            ? Expanded(
                              child: Center(
                                child: CircularProgressIndicator(
                                  color: Colors.white,
                                ),
                              ),
                            )
                            : Expanded(
                              child: Column(
                                children: [
                                  // 话题标题
                                  _buildTopicHeader(),

                                  // 评论输入框
                                  _buildCommentInput(),

                                  // 评论列表
                                  Expanded(child: _buildCommentsList()),
                                ],
                              ),
                            ),
              ),
            ],
          ),
        ),
      ),
    );
  }

  // 顶部导航栏
  Widget _buildAppBar() {
    return Container(
      height: 60.h,
      padding: EdgeInsets.symmetric(horizontal: 20.w),
      child: Row(
        children: [
          // 返回按钮
          InkWell(
            onTap: () => Navigator.pop(context),
            child: Icon(IconFont.back, color: Colors.white, size: 28.w),
          ),

          SizedBox(width: 10.w),

          Text(
            'Classic Perfume FAQ',
            style: TextStyle(
              color: Colors.white,
              fontSize: 20.sp,
              fontWeight: FontWeight.w600,
            ),
          ),

          Spacer(),

          // 信息按钮
          Icon(IconFont.report, color: Colors.white, size: 28.w),
        ],
      ),
    );
  }

  // 话题标题
  Widget _buildTopicHeader() {
    return Observer(
      builder:
          (_) => Container(
            width: double.infinity,
            padding: EdgeInsets.symmetric(horizontal: 20.w, vertical: 16.h),
            child: Text(
              _topicStore.topic?.question ?? '',
              style: TextStyle(
                color: Colors.white,
                fontFamily: 'Inter',
                fontSize: 18.sp,
                fontWeight: FontWeight.w400,
              ),
            ),
          ),
    );
  }

  // 评论列表
  Widget _buildCommentsList() {
    return Observer(
      builder: (_) {
        if (!_topicStore.hasComments) {
          return Center(
            child: Column(
              children: [
                Image.asset(
                  AssetsImages.empty,
                  width: 100.w,
                  height: 100.w,
                  fit: BoxFit.cover,
                ),
                SizedBox(height: 10.h),
                Text(
                  'No comments yet, be the first to comment',
                  style: TextStyle(color: Colors.white70, fontSize: 16.sp),
                ),
              ],
            ),
          );
        }

        return ListView.builder(
          padding: EdgeInsets.symmetric(horizontal: 24.w),
          itemCount: _topicStore.comments.length,
          itemBuilder: (context, index) {
            final comment = _topicStore.comments[index];
            return _buildCommentItem(comment);
          },
        );
      },
    );
  }

  // 评论项
  Widget _buildCommentItem(TopicCommentModel comment) {
    final user = comment.user;

    return Container(
      margin: EdgeInsets.only(bottom: 16.h),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          // 用户信息
          Row(
            children: [
              // 用户头像
              ClipRRect(
                borderRadius: BorderRadius.circular(20.r),
                child: Container(
                  width: 40.r,
                  height: 40.r,
                  color: Color(0xFFE7D3FF),
                  child:
                      user?.avatar != null
                          ? Image.asset(user!.avatar, fit: BoxFit.cover)
                          : Center(
                            child: Text(
                              user?.nickname.substring(0, 1).toUpperCase() ??
                                  'U',
                              style: TextStyle(
                                color: Color(0xFF9981B7),
                                fontSize: 18.sp,
                                fontWeight: FontWeight.bold,
                              ),
                            ),
                          ),
                ),
              ),
              SizedBox(width: 12.w),
              // 用户名称和时间
              Column(
                crossAxisAlignment: CrossAxisAlignment.start,
                children: [
                  Text(
                    user?.nickname ?? 'Unknown User',
                    style: TextStyle(
                      color: Color(0xFF150555),
                      fontSize: 14.sp,
                      fontWeight: FontWeight.w600,
                    ),
                  ),
                  Text(
                    _topicStore.formatTimestamp(comment.timestamp),
                    style: TextStyle(
                      color: Color(0xFF666666),
                      fontSize: 12.sp,
                      fontFamily: 'Inter',
                    ),
                  ),
                ],
              ),
            ],
          ),

          // 评论内容
          Padding(
            padding: EdgeInsets.only(top: 10.h),
            child: Text(
              comment.content,
              style: TextStyle(
                color: Color(0x66150555),
                fontSize: 13.sp,
                fontFamily: 'Inter',
              ),
            ),
          ),
        ],
      ),
    );
  }

  // 评论输入框
  Widget _buildCommentInput() {
    return Observer(
      builder: (_) {
        // 获取当前用户头像
        final avatarWidget =
            _topicStore.currentUser?.avatar != null
                ? ClipRRect(
                  borderRadius: BorderRadius.circular(21.r),
                  child: Container(
                    width: 42.r,
                    height: 42.r,
                    child: Image.asset(
                      _topicStore.currentUser!.avatar,
                      fit: BoxFit.cover,
                    ),
                  ),
                )
                : ClipRRect(
                  borderRadius: BorderRadius.circular(21.r),
                  child: Container(
                    width: 42.r,
                    height: 42.r,
                    color: Color(0xFFE7D3FF),
                    child: Center(
                      child: Text(
                        _topicStore.currentUser?.nickname
                                .substring(0, 1)
                                .toUpperCase() ??
                            'G',
                        style: TextStyle(
                          color: Color(0xFF9981B7),
                          fontSize: 16.sp,
                          fontWeight: FontWeight.bold,
                        ),
                      ),
                    ),
                  ),
                );

        // 如果是游客模式，显示登录提示
        if (!_topicStore.isUserLoggedIn) {
          return Container(
            padding: EdgeInsets.only(
              left: 20.w,
              right: 20.w,
              top: 10.h,
              bottom: 20.h,
            ),
            child: Row(
              children: [
                // 用户头像（游客）
                avatarWidget,

                SizedBox(width: 12.w),

                // 登录提示
                Expanded(
                  child: GestureDetector(
                    onTap: () => _topicStore.navigateToLogin(context),
                    child: Container(
                      height: 40.h,
                      padding: EdgeInsets.symmetric(horizontal: 16.w),
                      decoration: BoxDecoration(
                        color: Colors.white.withOpacity(0.7),
                        borderRadius: BorderRadius.circular(20.r),
                      ),
                      alignment: Alignment.centerLeft,
                      child: Text(
                        'Login to join the topic',
                        style: TextStyle(
                          color: Color(0xFF9981B7),
                          fontSize: 14.sp,
                        ),
                      ),
                    ),
                  ),
                ),
              ],
            ),
          );
        }

        // 已登录用户的评论输入框
        return Container(
          padding: EdgeInsets.only(
            left: 20.w,
            right: 20.w,
            top: 10.h,
            bottom: 20.h,
          ),
          child: Row(
            children: [
              // 用户头像
              avatarWidget,

              SizedBox(width: 12.w),

              // 输入框
              Expanded(
                child: Container(
                  height: 48.h,
                  decoration: BoxDecoration(
                    color: Colors.black.withOpacity(0.3),
                    borderRadius: BorderRadius.circular(24.r),
                  ),
                  child: TextField(
                    controller: _commentController,
                    textAlignVertical: TextAlignVertical.center,
                    style: TextStyle(
                      color: Colors.white,
                      fontSize: 14.sp,
                      fontFamily: 'Inter',
                    ),
                    decoration: InputDecoration(
                      hintText: 'Say something',
                      hintStyle: TextStyle(
                        color: Colors.white,
                        fontSize: 14.sp,
                        fontFamily: 'Inter',
                      ),
                      contentPadding: EdgeInsets.symmetric(
                        horizontal: 16.w,
                        vertical: 0,
                      ),
                      border: InputBorder.none,
                      isDense: true,
                      suffixIcon: GestureDetector(
                        onTap:
                            _topicStore.commentText.trim().isEmpty
                                ? null
                                : () => _topicStore.sendComment(widget.topicId),
                        child: Icon(
                          IconFont.send,
                          color: Colors.white,
                          size: 20.w,
                        ),
                      ),
                    ),
                  ),
                ),
              ),
            ],
          ),
        );
      },
    );
  }
}
